//
//  ExercisesContainViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/8.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "ExercisesContainViewController.h"
#import "ExercisesPageViewController.h"
#import "ExercisesItemTitleViewController.h"
#import "ExercisesQuestionChoiceViewController.h"
#import "ExercieseQuestionSubjectiveViewController.h"
#import "ExercieseQuestionReadingViewController.h"
#import "ExercisesQuestionBaseViewController.h"
#import "ExercisesAnswerCardViewController.h"
#import "ExercisesAnswerResultViewController.h"
#import "ExercieseQuestionItemModel.h"
#import "LessonUseageModel.h"
#import "ExercisesNormalAlertView.h"
#import "ExercisesFeedbackTypeView.h"
#import "ExercisesAnswerFeedbackView.h"
#import "ExercisesItemHeaderBarView.h"
#import "ExercisesResultHeaderBarView.h"
@interface ExercisesContainViewController ()<UIScrollViewDelegate>
@property (nonatomic,strong)UIScrollView *scrollView;
@property (nonatomic,strong)NSMutableArray *vcs;

@property (nonatomic,strong)ExercisesQuestionBaseViewController *lastVC;

@property (nonatomic,strong)ExercisesQuqestionModel *currentQuestionItem;

@property (nonatomic,assign)XHEnterType type;

@property (nonatomic,strong)ExercisesAnswerFeedbackView *feedbackView;

@property (nonatomic,strong)NSTimer *timer;

@property (nonatomic,strong)ExercisesItemHeaderBarView *itemBar;

@end

@implementation ExercisesContainViewController

- (NSMutableArray *)vcs{
    if (!_vcs) {
        _vcs = [NSMutableArray array];
    }
    return _vcs;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSInteger page = self.scrollView.contentOffset.x/kScreenW;
    UIViewController *vc = self.vcs[page];
    if ([vc isKindOfClass:[ExercisesQuestionBaseViewController class]]) {
        [(ExercisesQuestionBaseViewController *)vc startTimer];
    }
    // 开始定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshUseageTime) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    NSInteger page = self.scrollView.contentOffset.x/kScreenW;
    UIViewController *vc = self.vcs[page];
    if ([vc isKindOfClass:[ExercisesQuestionBaseViewController class]]) {
        [(ExercisesQuestionBaseViewController *)vc endTimer];
    }
    // 销毁定时器记录学习时间
    [self.timer invalidate];
    self.timer = nil;
}

- (instancetype)initWithDetailModel:(ExercisesPageModel *)model enterType:(XHEnterType)type{
    return [self initWithDetailModel:model selectedQuestionItem:nil enterType:type];
}

- (instancetype)initWithDetailModel:(ExercisesPageModel *)model selectedQuestionItem:(ExercisesQuqestionModel *)questionItem enterType:(XHEnterType)type{
    if (self = [super init]) {
        self.type = type;
        self.dtlModel = model;
        self.currentQuestionItem = questionItem;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
    [self registNote];
       
    // 判断是否是
    if (self.type == XHLESSONCONTAINENTERTRAGET) {
        __block NSInteger index = -1;
        [self.dtlModel.resultArray enumerateObjectsUsingBlock:^(ExercieseQuestionItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (self.currentQuestionItem && [obj.id isEqualToNumber:self.currentQuestionItem.id]) {
                obj.answerItem = self.currentQuestionItem.answerItem;
                index = idx;
                *stop = YES;
            }
        }];
        if (index != -1) {
            ExercisesQuestionBaseViewController *vc = self.vcs[index];
            [vc updateQuestionItem:self.dtlModel.resultArray[index]atIndex:index];
            
            if (index == 0 && self.dtlModel.resultArray.count > 1) {
                ExercisesQuestionBaseViewController *vc = self.vcs[index + 1];
                [vc updateQuestionItem:self.dtlModel.resultArray[index + 1]atIndex:index+1];
            }
            
            [self.scrollView setContentOffset:CGPointMake(kScreenW * index, 0) animated:YES];
        }
    }else{
        ExercisesPageModel *lastModel =[ExercisesPageModel getCurrentExercieseById:self.dtlModel.id];
        if (lastModel != nil) {
            NSInteger index = self.dtlModel.currentIndex;
            if (self.dtlModel.currentIndex == self.dtlModel.resultArray.count) {
                index = self.dtlModel.currentIndex - 1;
            }else{
                ExercieseQuestionItemModel *currentModel = self.dtlModel.resultArray[index];
                // 标题页面、主观题
                if (currentModel.type.intValue == 0 || currentModel.type.intValue == 5) {
                    index+=1;
                }else if (currentModel.type.intValue == 1){
                    index = currentModel.isMake?index+1:index;
                }
                // 判断下次俺是否是答题卡
                if (index == self.dtlModel.resultArray.count) {
                    index = index - 1;
                }else{
                    // 判断下一次是不是分页，如果是分页那就跳转下一题的下一题
                    ExercieseQuestionItemModel *nextModel = self.dtlModel.resultArray[index];
                    index = nextModel.type.intValue == 0?index+1:index;
                }
            }
            ExercieseQuestionItemModel *currentModel = self.dtlModel.resultArray[index];
            ExercisesQuestionBaseViewController *vc = self.vcs[index];
            [vc updateQuestionItem:currentModel atIndex:index];
            [self.scrollView setContentOffset:CGPointMake(kScreenW * index, 0) animated:YES];
        }
    }
    // Do any additional setup after loading the view.
}

- (void)setUI{
    [self setupScrollView];
}

- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nextPage) name:NEXTQUESTIONPAGE object:nil];
}
- (void)setupScrollView{
    
    if (self.type != XHLESSONCONTAINENTERNORMAL) {
        @zf_weakify(self)
        ExercisesResultHeaderBarView *resultView = [[ExercisesResultHeaderBarView alloc]initWithCompleteBlock:^{
            @zf_strongify(self)
            [self.navigationController popViewControllerAnimated:YES];
        } resultBlock:^{
            @zf_strongify(self)
            [self resultCardMethod];
        } moreBlock:^{
            @zf_strongify(self)
            [self feedbackMethod];
        }];
        
        if (self.type == XHLESSONCONTAINENTERRESULTERROR) {
            [resultView setNavTitle:@"错误解析"];
        }else{
            [resultView setNavTitle:@"查看解析"];
        }
        [self.view addSubview:resultView];
        
        [resultView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.height.mas_equalTo(44 + GK_STATUSBAR_HEIGHT);
        }];

    }else{
        
        @zf_weakify(self)
        self.itemBar = [[ExercisesItemHeaderBarView alloc]initWithCompleteBlock:^{
            @zf_strongify(self)
            [self back];
        } resultBlock:^{
            @zf_strongify(self)
            [self rightBarBtnAction];
        }];
        [self.view addSubview:self.itemBar];
        
        [self.itemBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.height.mas_equalTo(44 + GK_STATUSBAR_HEIGHT);
        }];
        
    }

    self.scrollView.backgroundColor = RGBA(248, 248, 248, 1);
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(44 + GK_STATUSBAR_HEIGHT);
        make.left.right.bottom.equalTo(self.view);
    }];
    // 添加到滚动视图
    [self addScrollView];
}

- (void)addScrollView{
    @zf_weakify(self)
    [self.dtlModel.resultArray enumerateObjectsUsingBlock:^(ExercieseQuestionItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        @zf_strongify(self)
        ExercisesQuestionBaseViewController *baseVC = [[ExercisesQuestionBaseViewController alloc]init];
        if (obj.type.intValue == 0) {
            baseVC = [[ExercisesItemTitleViewController alloc]init];
            ((ExercisesItemTitleViewController *)baseVC).isFirst = idx == 0;
        }
        if (obj.type.intValue == 1) {
            baseVC = [[ExercisesQuestionChoiceViewController alloc]init];
        }
        if (obj.type.intValue == 2) {
            baseVC = [[ExercieseQuestionReadingViewController alloc]init];
        }
        if (obj.type.intValue == 5) {
            baseVC = [[ExercieseQuestionSubjectiveViewController alloc]init];
        }
        
        // 普通进入
        if (self.type == XHLESSONCONTAINENTERNORMAL) {
            if (idx == 0) {
                // 设置遮盖
                [baseVC setupCoverView];
                // 赋值
                [baseVC updateQuestionItem:obj atIndex:idx];
                // 开启定时器
                [baseVC startTimer];
            }else if (idx == 1){
                // 设置遮盖
                [baseVC setupCoverView];
                // 赋值
                [baseVC updateQuestionItem:obj atIndex:idx];
            }
        // 错误解析 所有解析
        }else if (self.type == XHLESSONCONTAINENTERRESULTALL || self.type == XHLESSONCONTAINENTERRESULTERROR){
            if (idx == 0) {
                // 赋值
                [baseVC updateQuestionItem:obj atIndex:idx];
            }else if (idx == 1){
                // 赋值
                [baseVC updateQuestionItem:obj atIndex:idx];
            }
        }
        [self.scrollView addSubview:baseVC.view];
        [self addChildViewController:baseVC];
        [self.vcs addObject:baseVC];
        
    }];
    __weak typeof(self)weakSelf = self;
    // 普通进入最后一页增加答题卡页面
    if (self.type == XHLESSONCONTAINENTERNORMAL) {
        ExercisesAnswerCardViewController *cardVC = [[ExercisesAnswerCardViewController alloc]initWithItemModel:self.dtlModel enterType:XHENTERCARDADD];
        cardVC.isVideoFinish = self.isVideoFinish;
        [self.scrollView addSubview:cardVC.view];
        [self addChildViewController:cardVC];
        [self.vcs addObject:cardVC];
        
        cardVC.done = ^(ExercieseQuestionItemModel * _Nullable currentModel) {
            __block NSInteger index = -1;
            [weakSelf.dtlModel.resultArray enumerateObjectsUsingBlock:^(ExercieseQuestionItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.id isEqualToNumber:currentModel.id]) {
                    index = idx;
                    *stop = YES;
                }
            }];
            if (index != -1) {
               
                ExercisesQuestionBaseViewController *vc = weakSelf.vcs[index];
                
                [vc updateQuestionItem:currentModel atIndex:index];
            
                [weakSelf.scrollView setContentOffset:CGPointMake(kScreenW * index, 0) animated:YES];
            }
        };
    }
    self.scrollView.contentSize = CGSizeMake(kScreenW * self.vcs.count, 0);
    __block UIView *lastView = nil;
    [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (lastView == nil) {
            [obj mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.height.width.equalTo(self.scrollView);
                make.leading.mas_equalTo(self.scrollView.mas_leading);
            }];
        }else{
            [obj mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.height.width.equalTo(self.scrollView);
                make.leading.mas_equalTo(lastView.mas_trailing);
            }];
        }
        lastView = obj;
    }];
}

- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]init];
        _scrollView.pagingEnabled = YES;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
    }
    return _scrollView;
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self scrollViewDidEndDecelerating:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    // 取出当前页的数据
    NSInteger page = scrollView.contentOffset.x/kScreenW;
    
    NSInteger maxCount = self.type == XHLESSONCONTAINENTERNORMAL?self.vcs.count - 1:self.vcs.count;
    // 判断是否最后答题页
    if (page == maxCount && self.type == XHLESSONCONTAINENTERNORMAL) {
        // 取出卡片
        ExercisesAnswerCardViewController *cardVC = [self.vcs lastObject];
        // 赋值刷新  
        [cardVC updateCardItemStatus];
        // 设置头部UI
        [self.itemBar updateItemTitle:@"答题卡" andisHideRightItem:YES];
        
        [cardVC startTime];
        // 停止最后一道题目倒计时
        [self.lastVC endTimer];
    }else{
        // 普通进入
        if (self.type == XHLESSONCONTAINENTERNORMAL) {
            // 判断是否滑动进入答题卡页面
            ExercisesQuestionBaseViewController *currentVC = self.vcs[page];
            // 赋值操作
            [currentVC updateQuestionItem:self.dtlModel.resultArray[page] atIndex:page];
            // 停止答题卡的计时
            ExercisesAnswerCardViewController *cardVC = [self.vcs lastObject];
            //  答题卡停止计时
            [cardVC stopTime];
            // 设置头部UI
            [self.itemBar updateItemTitle:@"" andisHideRightItem:NO];
            // 判断当前vc和临时vc是否是同一个
            if (![currentVC isEqual:self.lastVC]) {
                // 停止计时
                [self.lastVC endTimer];
            }
            // 开始计算时间
            [currentVC startTimer];
            // 设置最后一个默认vc
            self.lastVC = currentVC;
        }
        // 取出后两页的数据
        NSInteger next = page + 1;
        NSInteger last = page - 1;
        if (next <= maxCount - 1) {
            ExercisesQuestionBaseViewController *vc = self.vcs[next];
            [vc updateQuestionItem: self.dtlModel.resultArray[next] atIndex:page];
        }
        if (last >= 0) {
            ExercisesQuestionBaseViewController *vc = self.vcs[last];
            [vc updateQuestionItem: self.dtlModel.resultArray[last] atIndex:page];
        }
    }
}

#pragma mark - itemMethod
- (void)rightBarBtnAction{
    //获取当前页面
    NSInteger page = self.scrollView.contentOffset.x/kScreenW;
    
    ExercisesQuestionBaseViewController *currentVC = self.vcs[page];
    
    [currentVC endTimer];
    
    ExercisesAnswerCardViewController *cardVC = [[ExercisesAnswerCardViewController alloc]initWithItemModel:self.dtlModel enterType:XHENETRCARDNORMAL];
    cardVC.isVideoFinish = self.isVideoFinish;
    NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:cardVC];

    [self presentViewController:nav animated:YES completion:^{
        [cardVC updateCoverViewStatus];
    }];
    
    __weak typeof(self)weakSelf = self;
    cardVC.done = ^(ExercieseQuestionItemModel *currentModel) {
        __strong typeof(weakSelf)strongSelf = weakSelf;
        __block NSUInteger index = -1;
        [strongSelf.dtlModel.resultArray enumerateObjectsUsingBlock:^(ExercieseQuestionItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.id isEqualToNumber:currentModel.id]) {
                index = idx;
                *stop = YES;
            }
        }];
        
        if (index != -1) {
            if (index == page) {
                [currentVC startTimer];
            }else{
                // 刷新当前控制视图
                ExercisesQuestionBaseViewController *currentVC = strongSelf.vcs[index];
                [currentVC updateQuestionItem:currentModel atIndex:index];
                // 页面滚动
                [strongSelf.scrollView setContentOffset:CGPointMake(kScreenW * index, 0) animated:YES];
            }
        }
    };
    
    cardVC.backResultCard = ^(ExercisesPaperResultModel * _Nullable res) {
        __strong typeof(weakSelf)strongSelf = weakSelf;
        ExercisesAnswerResultViewController *resultVC = [[ExercisesAnswerResultViewController alloc]init];
        resultVC.dtlModel = res;
        resultVC.isFinishVideo = self.isVideoFinish;
        [strongSelf.navigationController pushViewController:resultVC animated:YES];
    };
}

- (void)back{
    
    [self.lastVC endTimer];
    
    if (self.type != XHLESSONCONTAINENTERNORMAL) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        ExercisesNormalAlertView *alertView = [[ExercisesNormalAlertView alloc]initWithAlertTitle:@"退出练习？" message:@"我们会保留您的练习记录" confirmTitle:@"退出练习" cancelTitle:@"取消" confirmAciton:^{
            
            [MobClick event:@"exericese_card_close_confirm"];
            
            self.dtlModel.currentIndex = self.scrollView.contentOffset.x/kScreenW;
            
            [self.dtlModel save];
            
            
            if (self.isVideoFinish) {
                UIViewController *controller = self;
                while(controller.presentingViewController != nil){
                    controller = controller.presentingViewController;
                }
                [controller dismissViewControllerAnimated:YES completion:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                // 退出答题页上一个页面
                __block NSInteger index = -1;
                [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof RPBaseViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj isKindOfClass:[ExercisesPageViewController class]]) {
                        index = idx;
                        *stop = YES;
                    }
                }];
                if (index != -1) {
                    [self.navigationController popToViewController:self.navigationController.viewControllers[index-1] animated:YES];
                }else{
                    [self.navigationController popViewControllerAnimated:YES];
                }
                
            }
            

            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateAboutQuestionSource" object:nil userInfo:@{@"isFinish":@0}];
        } cancelAction:^{
            [self.lastVC startTimer];
            [MobClick event:@"exericese_card_close_cancel"];
        }];
        [alertView show];
    }
}

- (void)resultCardMethod{
    
    // 所有解析和指定跳转是同一种答题卡
    if (self.type == XHLESSONCONTAINENTERRESULTALL || self.type == XHLESSONCONTAINENTERTRAGET) {
        self.dtlModel.onlyError = NO;
        self.dtlModel.onlyQuestion = NO;
        self.dtlModel.errorQuestion = NO;
    }
    // 只显示错误答题卡
    if (self.type == XHLESSONCONTAINENTERRESULTERROR) {
        self.dtlModel.onlyError = NO;
        self.dtlModel.onlyQuestion = NO;
        self.dtlModel.errorQuestion = YES;
    }
    
    ExercisesAnswerCardViewController *cardVC = [[ExercisesAnswerCardViewController alloc]initWithItemModel:self.dtlModel enterType:XHENTERCARDRESULT];
    cardVC.isVideoFinish = self.isVideoFinish;
    NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:cardVC];
    
    [self presentViewController:nav animated:YES completion:^{
        [cardVC updateCoverViewStatus];
    }];
    
    __weak typeof(self)weakSelf = self;
    cardVC.done = ^(ExercieseQuestionItemModel *currentModel) {
        
        if (weakSelf.type == XHLESSONCONTAINENTERRESULTALL || weakSelf.type == XHLESSONCONTAINENTERTRAGET) {
            weakSelf.dtlModel.onlyError = NO;
            weakSelf.dtlModel.errorQuestion = NO;
            weakSelf.dtlModel.onlyQuestion = YES;
        }else if (weakSelf.type == XHLESSONCONTAINENTERRESULTERROR) {
            weakSelf.dtlModel.onlyError = YES;
            weakSelf.dtlModel.onlyQuestion = NO;
            weakSelf.dtlModel.errorQuestion = NO;
        }else{
            weakSelf.dtlModel.onlyError = NO;
            weakSelf.dtlModel.onlyQuestion = NO;
            weakSelf.dtlModel.errorQuestion = NO;
        }
        
        __block NSUInteger index = -1;
        [weakSelf.dtlModel.resultArray enumerateObjectsUsingBlock:^(ExercieseQuestionItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.id isEqualToNumber:currentModel.id]) {
                index = idx;
                *stop = YES;
            }
        }];
        if (index != -1) {
            ExercisesQuestionBaseViewController *currentVC = weakSelf.vcs[index];
            [currentVC updateQuestionItem:currentModel atIndex:index];
            // 页面滚动
            [weakSelf.scrollView setContentOffset:CGPointMake(kScreenW * index, 0) animated:YES];
        }
    };
}

- (void)feedbackMethod{
    __weak typeof(self)weakSelf = self;
    ExercisesFeedbackTypeView *typeView = [[ExercisesFeedbackTypeView alloc]initWithCompleteBlock:^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.feedbackView = [[ExercisesAnswerFeedbackView alloc]initWithCompleteBlock:^(NSString * _Nonnull content) {
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            param[@"content"] = content;
            param[@"md5"] = [RPAppManager md5StrWithApi:AddFeedback];
            param[@"userId"] = [RPAppManager getCustomerId];
            [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddFeedback) parames:param success:^(id responseObj) {
                [strongSelf.feedbackView hide];
                [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"感谢您的反馈，我们会努力进步的" duration:2 finishHandler:nil];
            } failure:^(id error) {

            }];
        }];
        [strongSelf.feedbackView show];
    }];
    [typeView show];
}

#pragma mark - 处理通知
- (void)nextPage{
    NSInteger page = self.scrollView.contentOffset.x/kScreenW;
    page += 1;
    if (page < self.vcs.count) {
        [self.scrollView setContentOffset:CGPointMake(kScreenW * page, 0) animated:YES];
    }
}
#pragma mark - 更新用户学习时间
- (void)refreshUseageTime{
    LessonUseageModel * model = [LessonUseageModel getUseage];
    NSInteger currentTime = model.currentTodayTime.intValue;
    currentTime+=1000;
    model.currentTodayTime = @(currentTime);
    [model save];
}
@end
